package com.netty.server.base;

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: 王霄
 * @date: 2022/1/19 16:17
 **/
@Slf4j
public class DefaultConnectionGroup implements ConnectionGroup {

    private final ConcurrentHashMap<String, Connection> connectionMap;

    public DefaultConnectionGroup() {
        this.connectionMap = new ConcurrentHashMap<>();
    }

    @Override
    public void register(Channel channel) {
        DefaultConnection connection = new DefaultConnection(channel);
        if (connection.getStatus() == ConnectStatus.ACTIVE) {
            connectionMap.putIfAbsent(connection.getId(), connection);
        }
    }

    @Override
    public Connection get(String id) {
        return Optional.ofNullable(id).map(connectionMap::get).orElse(null);
    }

    @Override
    public void del(String id) {
        Optional.ofNullable(id).map(connectionMap::remove).ifPresent(Connection::disconnect);
    }
}
